package ru.ds.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;

import ru.ds.selenium.util.*;

public class MainPage extends InternalPage {

  public MainPage(PageManager pages) {
	super(pages);
  }
	
  @FindBy(xpath = "//img[contains(@src,'add.png')]")
  private WebElement addImg;
	
  @FindBy(xpath = "//img[contains(@src,'update.png')]")
  private WebElement updateImg;
	
  @FindBy(xpath = "//img[contains(@src,'export_excel.png')]")
  private WebElement exportImg;
	
  @FindBy(xpath = "//input[@id='q']")
  private WebElement searchField;
  
  public void clickAddMovie() {
	  addImg.click();
  }
  
  public List<String> performSearch(String title) {
	  searchField.clear();
	  searchField.sendKeys(title);
	  WebElement oldElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='results']/*[1]")));
	  searchField.sendKeys(Keys.RETURN);
	  //wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@id='loading']")));
	  wait.until(ExpectedConditions.stalenessOf(oldElement));
	  List<String> lstMovieTitles = new ArrayList<String>();
	  WebElement firstChildElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='results']/*[1]")));
	  if(firstChildElement.getTagName().equals("a")) {
		  List<WebElement> lst = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(".//div[@id='results']/a//div[@class='title']")));
		  for(WebElement we : lst) {
			  lstMovieTitles.add(we.getText());
		  }
	  }
	  return lstMovieTitles;
  }
  
  public void clickMovieById(String Id) {
	  WebElement movieDiv = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='results']/a/div[contains(@id,'" + Id + "')]")));
	  movieDiv.click();
  }
  
  public MainPage clearSearchField() {
	  searchField.clear();
	  WebElement oldElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='results']/*[1]")));
	  searchField.sendKeys(Keys.RETURN);
	  //wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@id='loading']")));
	  wait.until(ExpectedConditions.stalenessOf(oldElement));
	  return this;
  }
  
  public MainPage ensurePageLoaded() {
    super.ensurePageLoaded();
    wait.until(presenceOfElementLocated(By.xpath("//div[@id='results']")));
    return this;
  }
}